package com.et114.components.gzip;

import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * @author guanhw
 */

public class GZipTools {
	
	/**
	 * 
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	public static void writeGZip ( InputStream in , OutputStream out , boolean close ) throws IOException {
		GZIPOutputStream gzout = new GZIPOutputStream ( out );
		byte [ ] buf = new byte [ 1024 ];// 设定读入缓冲区尺寸
		int num;
		
		while ( ( num = in.read ( buf ) ) != - 1) {
			gzout.write ( buf , 0 , num );
		}
		gzout.flush ( ) ; 
		gzout.close ( );//
		if ( close ) {
			out.close ( );
			in.close ( );			
		}
	}
	
	/**
	 * 
	 * @param in
	 * @param out
	 * @param close
	 * @throws IOException
	 */
	public static void writeUnGZip( InputStream in , OutputStream out , boolean close ) throws IOException {
		GZIPInputStream gzin = new GZIPInputStream ( in );
		//建立解压文件输出流 
		byte [ ] buf = new byte [ 1024 ];
		int num; 
		
		while ( ( num = gzin.read ( buf , 0 , buf.length ) ) != - 1) {
			out.write ( buf , 0 , num );
		}
		gzin.close ( );
		if ( close ) {
			out.close ( );
			in.close ( );			
		}		
	}
	
	
	/**
	 * 
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static byte[ ] writeGZip ( String str  )  throws Exception {
		ByteArrayOutputStream bout = new ByteArrayOutputStream(  ) ; 
		GZIPOutputStream gout = new GZIPOutputStream( bout );
		ObjectOutputStream obj = new ObjectOutputStream( gout ) ; 
		obj.writeBytes ( str ) ; 
		obj.flush ( );
		obj.close ( ) ; 
		return  bout.toByteArray ( ) ; 
	} 
	
	
	/**
	 * 
	 * @param bs
	 * @return
	 * @throws Exception
	 */
	public static String readGZip( byte[] bs )  throws Exception  {
		ByteArrayInputStream i = new ByteArrayInputStream ( bs );
		GZIPInputStream gzin = new GZIPInputStream ( i );
		ObjectInputStream br = new ObjectInputStream( gzin ) ; 
		String tmp = null ; 
		StringBuffer sb = new StringBuffer( ) ; 
		while( ( tmp = br.readLine ( ) ) != null  ) {
			sb.append ( tmp ) ; 
			sb.append ( "\n" ) ;
		} 
		return sb.toString ( ) ; 
	}
	
	
	
	public static void main( String[] ss ) throws Exception {
		String emp = "ddddddddd  sssssssssssss" ; 
		byte[] bs = writeGZip( emp ) ; 
		emp = readGZip( bs ) ;
		System.out.println (  emp  ) ;
		
		
		FileInputStream input  = new FileInputStream( "d:/AcegiCacheManager.java" ) ;
		FileOutputStream out  = new FileOutputStream( "d:/AcegiCacheManager.java.zip") ;
		writeGZip( input , out , true ) ;
		
		//writeUnGZip( input , out , true ) ;
	}
}
